import React, { useEffect } from 'react';

import { Button, Card, Form, Input } from 'antd';

import { BottomAction } from '@/components';
import OrganizationSelect from '@/components/OrganizationSelect';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { defaultFormatResult, useRequest } from '@/hooks';
import { formatResultByFetchDetail, onSuccessBySave } from '@/pages/TurnoverSetting/EntrySetting/util';
import { getDict } from '@/utils/dataDictUtil';
import pageTabUtil from '@/utils/pageTabUtil';

import { TemplateEditor } from '@/pages/TurnoverSetting/EntrySetting/components';
import styles from './index.less';
import { getLeavingProveDefaultConfig, getLeavingProveDetail, handleLeavingProve } from '../services';

/**
 * 离职证明模板
 */
const DemissionCertEdit = ({ form, location }) => {
    const { query } = location;
    const { getFieldDecorator } = form;
    const [dictList, setDictList] = React.useState([]);

    const isAddPage = React.useMemo(() => {
        const { pathname = '' } = location;
        return pathname.includes('add');
    }, [location]);

    // 如果是新增的情况，写入默认邮件模板
    const { data: defaultEmailTemplate, run: fetchEmailTemplate } = useRequest(getLeavingProveDefaultConfig, {
        manual: true,
        ...defaultFormatResult
    });

    // 获取通知模板
    const { data, loading, run: fetchTemplate } = useRequest(getLeavingProveDetail, {
        manual: true,
        formatResult: formatResultByFetchDetail
    });

    // 保存
    const { loading: saveLoading, run: saveTemplate } = useRequest(handleLeavingProve, {
        manual: true,
        onSuccess: (res, options) => onSuccessBySave(res, options, '4')
    });

    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                // const { mailAttachments } = values;
                const params = {
                    isDefault: data?.isDefault ?? 0,
                    ...values,
                    // mailAttachments: mailAttachments?.uploadResourceFile
                    //     ? mailAttachments?.uploadResourceFile?.keyNameAndOpt
                    //     : [],
                    templateContent: values.templateContent
                        .replace(/<span data-foo="/g, '${')
                        .replace(/" data-id="[0-9]+" class="column-item">[\u4e00-\u9fa5]+<\/span>/g, '}')
                };
                if (!isAddPage) {
                    params.id = query?.id;
                }
                saveTemplate(params);
            }
        });
    };

    // 获取邮件插入参数数据字典
    useEffect(() => {
        getDict('paramOfDimissionProveMail').then(ret => {
            const dict = ret && ret.map(e => ({ field: e.dictValue, value: e.dictName }));
            setDictList(dict);
        });
    }, []);

    useEffect(() => {
        if (query?.id) {
            fetchTemplate(query?.id);
        }
    }, [query]);

    React.useEffect(() => {
        if (isAddPage) {
            fetchEmailTemplate(1);
        }
    }, []);

    return (
        <PageHeaderWrapper>
            <Card
                title={isAddPage ? '添加离职证明模板' : '编辑离职证明模板'}
                bordered={false}
                loading={loading}
                extra={
                    <BottomAction>
                        <Button onClick={() => pageTabUtil.goBack()}>取消</Button>
                        <Button type="primary" onClick={handleSubmit} loading={saveLoading}>
                            确定
                        </Button>
                    </BottomAction>
                }
            >
                <Form className={styles.formWrap} style={{ marginTop: 24 }}>
                    <Form.Item label="模板名称">
                        {getFieldDecorator('templateName', {
                            initialValue: data?.templateName,
                            rules: [
                                {
                                    required: true,
                                    message: '请输入模板名称'
                                }
                            ]
                        })(<Input placeholder="请输入模板名称" allowClear maxLength={200} style={{ maxWidth: 528 }} />)}
                    </Form.Item>
                    <Form.Item label="适用行政机构">
                        {data?.hasDefault && '全集团'}
                        {
                            data?.hasDefault && form.getFieldDecorator('companyCodeList', {
                                initialValue: data?.companyCodeList || undefined
                            })(<input type="hidden" />)
                        }
                        {
                            !data?.hasDefault && getFieldDecorator('companyCodeList', {
                                initialValue: data?.companyCodeList,
                                rules: [{
                                    required: true,
                                    message: '请选择行政机构'
                                }]
                        })(
                            <OrganizationSelect
                                isStrictly
                                maxTagCount={2}
                                isNeedPermission={false}
                                onlyCompany
                                treeCheckable
                                style={{ maxWidth: 528 }}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="模板正文">
                        {form.getFieldDecorator('templateContent', {
                            rules: [
                                {
                                    required: true,
                                    message: '模板正文不能为空'
                                }
                            ]
                        })(
                            <TemplateEditor
                                initialValue={data?.templateContent || defaultEmailTemplate?.templateContent}
                                contentStyle={{ height: 'auto', minHeight: 250 }}
                                insertParamList={dictList} // 要参数的参数由外部引入
                            />
                        )}
                    </Form.Item>
                </Form>
            </Card>
        </PageHeaderWrapper>
    );
};

export default React.memo(Form.create()(DemissionCertEdit));
